package com.zjj.lbw.microservice.seata.order.seataorderservice.service.impl;

import com.zjj.lbw.microservice.seata.mysqlcommon.datasource.entity.Order;
import com.zjj.lbw.microservice.seata.order.seataorderservice.feign.AccountFeignService;
import com.zjj.lbw.microservice.seata.order.seataorderservice.feign.StorageFeignService;
import com.zjj.lbw.microservice.seata.order.seataorderservice.service.BussinessService;
import com.zjj.lbw.microservice.seata.order.seataorderservice.service.TCCOrderService;
import com.zjj.lbw.microservice.seata.order.seataorderservice.util.UUIDGenerator;
import com.zjj.lbw.microservice.seata.order.seataorderservice.vo.OrderVo;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author zhanglei.zjj
 */
@Service
@Slf4j
public class BusinessServiceImpl implements BussinessService {

    @Autowired
    private AccountFeignService accountFeignService;

    @Autowired
    private StorageFeignService storageFeignService;

    @Autowired
    private TCCOrderService tccOrderService;


    @Override
    @GlobalTransactional(name = "createOrder", rollbackFor = Exception.class)
    public Order saveOrder(OrderVo orderVo) {
        log.info("=============用户下单=================");
        log.info("当前 XID: {}", RootContext.getXID());

        //获取全局唯一订单号  测试使用
        Long orderId = UUIDGenerator.generateUUID();

        //阶段一： 创建订单
        Order order = tccOrderService.prepareSaveOrder(orderVo, orderId);

        //扣减库存
        storageFeignService.tccDeduct(orderVo.getCommodityCode(), orderVo.getCount());

        //扣减余额
        accountFeignService.tccDebit(orderVo.getUserId(), orderVo.getMoney());

        return order;
    }
}
